import React, { Component, Fragment } from 'react';
import ReactDOM from 'react-dom';
import { connect } from 'dva';
import { Modal, Form, Button, Select, Input, Row, Col, Spin, Icon, Checkbox, Tooltip } from 'antd';
import prompt from '@/components/Prompt';
import StandardTable from '@/components/StandardTable';
import SearchSelect from '@/components/SearchSelect';
import AdModal from '@/components/AdModal';
import AntdForm from '@/components/AntdForm';
import AdSelect from '@/components/AdSelect';
import AdButton from '@/components/AdButton';
import AntdFormItem from '@/components/AntdFormItem';
import AntdInput from '@/components/AntdInput';
import AntdSelectRegion from '@/components/AntdSelectRegion';
import EditPage from '@/components/EditPage';
import ExportAdrList from './ExportAddressList';
import { allDictList } from '@/utils/constans';
import { formItemFragement } from '@/utils/common';
import { allDispatchType, allUrl } from '../utils';
import styles from '../exportOs.less';
import { transferLanguage } from '@/utils/utils';
import { languages } from 'monaco-editor';


const { Option } = Select;
const { TextArea } = Input;
const { confirm } = Modal;

@connect(({ i18n }) => ({
  language: i18n.language,
}))
@Form.create()
export default class ExportAddress extends Component {
  state = {
    visibleAdrList: false,
    isChecked: false,
    addressInfo: {},
  };

  componentDidMount() {
    const { p_addressInfo } = this.props;
    this.setState(
      {
        addressInfo: p_addressInfo,
      },
      () => {
        if (p_addressInfo && p_addressInfo.fullParentIds) {
          // this.formatAddress(p_addressInfo.fullParentIds)
        }
      }
    );
  }

  componentWillMount() {}

  //通过填写的详细地址--获取城市
  getCity = () => {
    const { dispatch, form } = this.props;
    const address = form.getFieldValue('address');
    if (!address) {
      prompt({
        title: '提示',
        content: '请填写详细地址',
        type: 'error',
      });
      return;
    }
    dispatch({
      type: allDispatchType.getAddress,
      payload: { address: address || '' },
      callback: data => {
        if (!data) return;
        // this.formatAddress(data.fullParentIdss);
      },
    });
  };

  //设置弹窗
  setAdrListModal = () => {
    this.setState(pre => ({
      visibleAdrList: !pre.visibleAdrList,
    }));
  };

  formateIds = val => {
    if (val instanceof Array) {
      return val.join(',');
    }
    return val;
  };

  //保存地址：
  saveAddress = () => {
    const { addressType, form, dispatch, getAddressInfo } = this.props;
    const { addressInfo } = this.state;
    form.validateFieldsAndScroll((err, values) => {
      if (err) {
        return;
      }
      const { allAddress, isChecked, ...value } = values;

      const newParams = { ...addressInfo, ...value };
      let typeInfo = addressType + 'Address';
      newParams.fullParentIds = this.formateIds(newParams.fullParentIds);
      //有id并且选中就保存到数据库,没有id勾选保存到数据库
      if (addressInfo.id || (!addressInfo.id && isChecked)) {
        newParams.id = addressInfo.id;
        newParams.isDefault = addressInfo.id ? isChecked : false;
        dispatch({
          type: allDispatchType.operateAddress,
          payload: { ...newParams },
          callback: data => {
            getAddressInfo(typeInfo, newParams);
          },
        });
      } else {
        getAddressInfo(typeInfo, newParams);
      }
    });
  };

  //选择：
  changeChecked = (e, type) => {
    this.setState({
      [type]: e.target.checked,
    });
  };

  //获取选择的列表地址： 统一返回地址的数据格式为 字符串
  getChoiceAddress = address => {
    const { addressType } = this.props;
    this.setState(
      {
        addressInfo: address,
        visibleAdrList: false,
      },
      () => {
        // this.formatAddress(address.fullParentIds)
      }
    );
  };

  //格式化地址 默认值（initialValue）改变自动更新视图，无需form.setFieldsValue设置
  formatAddress = (data, type) => {
    const { form } = this.props;
    let newData = data ? data.split(',') : [];
    if (newData.length > 0 && newData[0] == '0') {
      newData.shift();
    }
    if (newData.length > 4) {
      newData = newData.slice(0, 4);
    } else if (newData.length > 2 && newData.length < 4) {
      //增加数组元素，为了统一使用组件回显
      newData.length = 4;
    }
    newData = newData.join(',');
    // this.setState({
    //     addressInfo: {
    //         ...this.state.addressInfo,
    //         fullParentIds: newData,
    //     }
    // });
    // form.setFieldsValue({ 'fullParentIds': newData })
  };
  //识别地址：
  discernFn = () => {
    const { form, dispatch } = this.props;
    const address = form.getFieldValue('allAddress');
    if (!address) {
      prompt({
        type: 'warn',
        content: '请输入地址',
      });
      return;
    }
    dispatch({
      type: allDispatchType.discernAddress,
      payload: { address },
      callback: res => {
        let addressInfo = {
          name: res.name,
          phone: res.mobile || res.phone,
          address: res.detail,
          fullParentIds: [res.provinceId, res.cityId, res.countyId].join(','),
          fullParentNames: res.provinceName + res.cityName + res.countyName,
        };
        this.setState({
          addressInfo: addressInfo,
        });
        // this.formatAddress(addressInfo.fullParentIds);
        getAddressInfo(typeInfo, addressInfo);
      },
    });
  };
  //清空地址：
  clearn = () => {
    const { form } = this.props;
    form.setFieldsValue({ allAddress: '' });
  };
  //获取城市名称：
  getRegionName = name => {
    this.setState({
      addressInfo: {
        ...this.state.addressInfo,
        fullParentNames: name,
      },
    });
  };

  render() {
    const {
      form: { getFieldDecorator },
      disabled,
      userToken,
      addressType,
      setAddressModal,
      visibleAddress,
      p_addressInfo,
      language
    } = this.props;
    const { visibleAdrList, isChecked, addressInfo } = this.state;

    const commonParams = {
      getFieldDecorator,
    };
    const formItem = [
      [
        <AntdFormItem
          label={transferLanguage('MyOrder.field.name', language)}
          code="name"
          rules={[{ required: true }]}
          initialValue={addressInfo.name}
          {...commonParams}
        >
          <AntdInput disabled={disabled} />
        </AntdFormItem>,
        <AntdFormItem
          label={transferLanguage('MyOrder.field.phone', language)}
          code="phone"
          initialValue={addressInfo.phone}
          rules={[{ required: true }]}
          {...commonParams}
        >
          <AntdInput disabled={disabled} />
        </AntdFormItem>,
      ],
      [
        <AntdFormItem
          label={transferLanguage('MyOrder.field.city', language)}
          code="fullParentIds"
          initialValue={addressInfo.fullParentIds}
          rules={[{ required: true }]}
          {...commonParams}
        >
          <AntdSelectRegion
            url="api/Common/Area/GetAreaById"
            paramsLabel="id"
            label={transferLanguage('MyOrder.field.address', language)}
            disabled={disabled}
            split=","
            defaultId="44857702471028736"
            requestType="get"
            limitLevel="3"
            getRegionName={this.getRegionName}
          />
        </AntdFormItem>,
        <AntdFormItem
          label={transferLanguage('MyOrder.field.detailedAddress', language)}
          code="address"
          initialValue={addressInfo.address || userToken.address}
          rules={[{ required: true }]}
          {...commonParams}
        >
          <AntdInput
            disabled={disabled}
            // addonAfter={<Tooltip title="点击获取--城市">
            //     <Icon type="api" onClick={() => this.getCity()} />
            // </Tooltip>}
          />
        </AntdFormItem>,
      ],
      [
        <div className="cus_removeColon">
          <AntdFormItem
            label=" "
            code="isChecked"
            initialValue={isChecked || false}
            {...commonParams}
          >
            <Checkbox
              checked={isChecked || false}
              onChange={val => this.changeChecked(val, 'isChecked')}
            >
              {addressInfo.id ? transferLanguage('MyOrder.field.setDefaultAddress', language) : transferLanguage('MyOrder.field.saveAddress', language)}
            </Checkbox>
          </AntdFormItem>
        </div>,
        <></>,
      ],
    ];
    const formItemDiscern = [
      [
        <AntdFormItem label={transferLanguage('MyOrder.field.AddressRecognition', language)} code="allAddress" initialValue={''} {...commonParams}>
          <AntdInput
            disabled={disabled}
            type="textarea"
            placeholder="粘贴地址信息,自动拆分姓名/电话和地址"
            rows="4"
          />
        </AntdFormItem>,
      ],
    ];
    const _gutter = { md: 8, lg: 24, xl: 48 };
    const _col = { md: 12, sm: 24 };
    const _row = { md: 24 };
    return (
      <AdModal
        visible={visibleAddress}
        title={`${transferLanguage('MyOrder.field.add', language)}${addressType == 'spickup' ? transferLanguage('MyOrder.field.consignor', language) : transferLanguage('MyOrder.field.consignee', language)}${transferLanguage('MyOrder.field.address', language)}`}
        onOk={this.saveAddress}
        onCancel={() => setAddressModal()}
        width="60%"
        style={{
          maxWidth: 800,
        }}
      >
        <div className={styles.cusModal}>
          <div className={styles.addressfromList}>
            <span onClick={() => this.setAdrListModal()} style={{ display: 'inline-block' }}>
              {' '}
              <Icon type="contacts" style={{ marginRight: 6 }} />
              
              {transferLanguage('MyOrder.field.GetItFromTheAddressBook', language)}
              
            </span>
          </div>
          <AntdForm>{formItemFragement(formItem)}</AntdForm>
          <div className={styles.discernBox}>
            {/* <AntdForm>{formItemFragement(formItemDiscern)}</AntdForm> */}
            <Row gutter={_gutter} className="discernBox">
              <Col {..._row}>
                <Form.Item label="">
                  {getFieldDecorator('allAddress', {
                    initialValue: '',
                  })(
                    <AntdInput
                      disabled={disabled}
                      type="textarea"
                      placeholder="粘贴地址信息,自动拆分姓名/电话和地址"
                      rows="3"
                    />
                  )}
                </Form.Item>
              </Col>
            </Row>
            <div className={styles.hasContent} style={{ textAlign: 'right', fontSize: 13 }}>
              <span className={styles.del_discern} onClick={() => this.clearn()}>
                <Icon type="delete" />
                {transferLanguage('MyOrder.field.empty', language)}
              </span>
              <span className={styles.btn_discern} onClick={this.discernFn}>
                {transferLanguage('MyOrder.field.identify', language)}
              </span>
            </div>
          </div>

          {visibleAdrList && (
            <ExportAdrList
              visibleAdrList={visibleAdrList}
              setAdrListModal={this.setAdrListModal}
              userToken={this.userToken}
              getChoiceAddress={this.getChoiceAddress}
            />
          )}
        </div>
      </AdModal>
    );
  }
}
